
$(function(){
	
	jQuery.support.cors = true;

	var thisElement,
			thispage = 0;


	$("#template ul").on("click","li",function(event){
		thisElement = $(this);
		if(thisElement.attr('class') === 'active') return ;
		var id = {'id':thisElement.attr('data-id')};
		
		swal({
			icon: "warning",
			title: "제시",
			text: "템플릿을 사용한후에는 기존 화면상 모든 내용을 덮어버릴 수 있습니다",
			buttons: {
				ok: "확인",
				no:  "취소",
			},
			closeOnClickOutside: false,
		})
		.then((value) => {
			switch (value) {
			case "ok":
				$.ajax({
					'url': templateApi,
					'type': 'get',
					'data': id,
					beforeSend: function () {
						swal({icon: 'success',className: 'alertloading',button:false,closeOnClickOutside: false});
					},
					success: function(data) {
						if(data.template !== undefined){
							loadTemplate(data.template);
						}else {
							swal('ERRO', 'can not fond template', 'error')
						}
					},
					error: function(xhr, stat, err) {
						if(xhr.status != 404 && xhr.responseText) {
							loadSvgString(xhr.responseText);
						} else {
							swal('ERRO', uiStrings.notification.URLloadFail + ": \n"+err+'', 'error')
						}
					}
				});
				break;
			case "no":
				swal.close()
			}
		});
	})

	
	var templateActive = function(){ //标记当前编辑页
		thispage = 0;
		thisElement.siblings().removeClass('active').end().addClass('active'); 
	}

	var svgLoadFromURL = function(url,callback) { //ajax获取svg
		$.ajax({
			'url': url,
			'dataType': 'text',
			success: function(str) {
				methodDraw.loadFromString(str);
				autoZoom();
				clearActions();
				if(callback !== undefined){
					callback();
				}
				setTimeout(function(){
					swal.close();
				},300);
			},
			error: function(xhr, stat, err) {
				if(xhr.status != 404 && xhr.responseText) {
					loadSvgString(xhr.responseText);
				} else {
					swal('ERRO', uiStrings.notification.URLloadFail + ": \n"+err+'', 'error')
				}
			}
		});
	};
	





	var loadTemplate = function(template){  //载入模板
		
		localStorage.setItem('template',JSON.stringify(template));
		
		var pagelist = '';
		for ( var i=0; i< template.length; i++) {
			if(i===0){
				svgLoadFromURL(template[i].url,templateActive);
			}
			localStorage.setItem('page'+i,template[i].url);
			pagelist += '<li><img src="'+template[i].thumbnail+'" data-svg="'+template[i].url+'"><span>'+template[i].name+'</span></li>'
			$('#template_page ul').html(pagelist);
			
			
			$('#template_page ul li').click(function(){
				loadpage($(this).index());
				
			})
		}
		
		
		
		
	}

	var loadpage = function(num){ 	//切换页面
		svgCanvas.clearSelection();//取消选择
		
		localStorage.setItem('page'+thispage,svgCanvas.svgCanvasToString());//保存当前页面
		
		clearActions();//停止一切当前操作
		
		if(localStorage.getItem('page'+num).length < 100){
			swal({icon: 'success',className: 'alertloading',button:false,closeOnClickOutside: false});
			svgLoadFromURL(localStorage.getItem('page'+num));
		}else{
			methodDraw.loadFromString('<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg"></svg>');//载入空页
			methodDraw.loadFromString(localStorage.getItem('page'+num)); //切换页面
			autoZoom();	
			clearActions();
		}
		thispage = num;
		
	}

	var resetTemplate = function(){ //初始化模板
		var svgurl = localStorage.getItem("template");
		loadTemplate(JSON.parse(svgurl));
	}


	$('#reload_svg').click(function(){  //初始化模板
		swal({
			icon: "warning",
			title: "제시",
			text: "초기화는 그동안 편집한 내용을 지워버릴 수 입습니다.",
			buttons: {
				ok: "확인",
				no:  "취소",
			},
			closeOnClickOutside: false,
		})
		.then((value) => {
			switch (value) {
			case "ok":
				resetTemplate();
				break;
			case "no":
				swal.close()
			}
		});
	});


	var autoZoom = function(){ //调整尺寸为全画面
		var canvasWidth = $('#svgroot').attr('width');
		var canvasHeight = $('#svgroot').attr('height');
		var svgWidth = $('#svgcontent').attr('width');
		var svgHeight = $('#svgcontent').attr('height');
		if(canvasWidth > svgWidth && canvasHeight > svgHeight){
			var widthRate = Math.floor(canvasWidth/svgWidth);
			svgCanvas.setZoom(2.5);
			methodDraw.updateCanvas();
			var now_zoom_leve = svgCanvas.getZoom();
			$('#zoom_posint').text(now_zoom_leve*100+'%');
		}
	}

	var clearActions = function(){ //停止一切当前操作
		svgCanvas.clearSelection(); // 取消选择元素
		svgCanvas.pathActions.clear(); //停止曲线动作
		svgCanvas.textActions.clear(); //停止编辑文字动作
		$('#tool_undo').addClass('disabled');
		$('#tool_redo').addClass('disabled');
		svgCanvas.undoMgr.resetUndoStack(); //清除历史记录
	}
	


	//加粗
	$('#font_b').click(function(){
		$(this).toggleClass('active');
		svgCanvas.setBold( !svgCanvas.getBold());
	});
	//斜体
	$('#font_i').click(function(){
		$(this).toggleClass('active');
		svgCanvas.setItalic( !svgCanvas.getItalic());
	});
	//左对齐
	$('#font_algin_left').click(function(){
		if(selectedElements[0].getAttribute('text-anchor') !== 'start'){
			svgCanvas.changeSelectedAttribute('text-anchor','start');
			$(this).siblings().removeClass('active').end().addClass('active');
		}
	});
	//居中对齐
	$('#font_algin_center').click(function(){
		if(selectedElements[0].getAttribute('text-anchor') !== 'middle'){  //如果不为居中 则设置居中
			svgCanvas.changeSelectedAttribute('text-anchor','middle');
			$(this).siblings().removeClass('active').end().addClass('active');
		}else{
		}
		
	});
	//右对齐
	$('#font_algin_right').click(function(){
		if(selectedElements[0].getAttribute('text-anchor') !== 'end'){
			svgCanvas.changeSelectedAttribute('text-anchor','end');
			$(this).siblings().removeClass('active').end().addClass('active');
		}else{
		}
	});
	
	//增加字号
	$('.font_size .up').click(function(){
		var plusFontSize = parseInt(selectedElements[0].getAttribute('font-size'));
		svgCanvas.setFontSize(plusFontSize+1);
		$('#font_size').val(plusFontSize+1);
	});
	//减小字号
	$('.font_size .down').click(function(){
		var plusFontSize = parseInt(selectedElements[0].getAttribute('font-size'));
		svgCanvas.setFontSize(plusFontSize-1);
		$('#font_size').val(plusFontSize-1);
	});
	//修改字体
	
	
	$('#font_family_value').click(function(){
		
		if($('#color_picker_master').css('display')==='block'){
			$('#color_picker_master').css('display','none');
		}

		if($('#color_pick_list').attr('class')==='show'){
			$('#color_pick_list').removeClass('show');
		}
		if($('#font_family_pick').attr('class')==='show'){
			$('#font_family_pick').removeClass('show');
			return false;
		}else{
			$('#font_family_pick').addClass('show');
			return false;
		}
	});
	
	$('#font_family_pick ul li').click(function(){
		$('#font_family_value span').text($(this).attr('data-font-family'));
		svgCanvas.setFontFamily($(this).attr('data-font-family'));
		$('#font_family_pick').removeClass('show');
		$('#font_family_value span').css('font-family',$(this).attr('data-font-family'));
		$(this).siblings().removeClass('active').end().addClass('active');
	});
	
	//修改字体颜色
	$('#color_pick_value').click(function(){
		if($('#color_picker_master').css('display')==='block'){
			$('#color_picker_master').css('display','none');
		}
		if($('#font_family_pick').attr('class')==='show'){
			$('#font_family_pick').removeClass('show');
		}
		if($('#color_pick_list').attr('class')==='show'){
			$('#color_pick_list').removeClass('show');
			return false;
		}else{
			$('#color_pick_list').addClass('show');
			return false;
		}
	});
	
	$('#color_pick_list li').click(function(){
		if($(this).attr('id')!=='color_pick_custom'){
			
			$('#color_pick_value').css('background',$(this).css('background'));
			svgCanvas.setFontColor($(this).css('background-color'));
		}
	})
	
	//初始化 颜色选择器
	$('#color_pick_custom').click(function(){
		if($('#color_picker_master').css('display')!=='block'){
			$('#color_picker_master').css('display','block');
			return false;
		}
	})
	var cpDefault = ColorPicker(document.getElementById('color_picker_master'), updateInputs);
	function updateInputs(hex) {
	    $('#color_pick_value').css('background',hex);
			svgCanvas.setFontColor(hex);
	}

	
	//服务器状态码处理
	var statusCode = function(code){
		switch (code)
		{
		case 200:
			return true;
			break;
		case 301:
		  swal('301', 'No User', 'error');
		  return false;
		  break;
		case 302:
			swal('302', 'Password Error', 'error');
			return false;
			break;
		case 303:
			swal('303', 'Unknown error Try again later.', 'error');
			return false;
			break;
		case 304:
			swal('304', 'The account has already been logged out.', 'error');
			return false;
			break;
		case 305:
			swal('305', 'The name does not match the token. Please check the data.', 'error');
			return false;
			break;
		case 306:
			swal('306', 'Login timeout.', 'info');
			return false;
			break;	
		case 401:
			swal('401', 'Invalid Token.', 'info');
			return false;
			break;	
		case 402:
			swal('402', 'The other clients have already logged in.', 'info');
			return false;
			break;	
		case 403:
			swal('403', 'Token expired.', 'info');
			return false;
			break;	
		case 405:
			swal('405', 'No query results.', 'info');
			return false;
			break;	
		case 501:
			swal('501', 'No Post/Get Data.', 'info');
			return false;
			break;
		case 502:
			swal('502', 'No Api.', 'info');
			return false;
			break;
		case 602:
			swal('602', 'File upload exception, please check.', 'info');
			return false;
			break;	
		}
	}
	
	

	//搜索模板
	
	var searchTemplate = function(){
		if($('#template .keyword').val() === '') return false;
		var keyword = {'keyword':$('#template .keyword').val()};
		$.ajax({
			'url': templateSearchApi,
			'type': 'get',
			'data': keyword,
			beforeSend: function () {
				swal({icon: 'success',className: 'alertloading',button:false,closeOnClickOutside: false});
			},
			success: function(data) {
				if(!statusCode(data.code)) return false;
				var list = '';
				for(var i=0; i<data.list.length; i++){
					list += '<li data-id="'+ data.list[i].id+'">';
					list += '<div class="editing"><span><i></i></span></div>';
					list += '<div class="template-thumbnail">';
					list += '<img src="'+data.list[i].thumbnail+'">';
					list += '</div>';
					list += '</li>';
				}
				$('#template ul').html(list);
				$('#template .keyword').val('');
				swal.close();
			},
			error: function(xhr, stat, err) {
				if(xhr.status != 404 && xhr.responseText) {
					loadSvgString(xhr.responseText);
				} else {
					swal('ERRO', uiStrings.notification.URLloadFail + ": \n"+err+'', 'error')
				}
			}
		});
	}
	
	$("#template .keyword").keypress(function(e){
		if (e.which == 13) {
			searchTemplate();
		}
	});
	$('#template .search .submit').click(function(){
		searchTemplate();
	});
	
	
	//获取模板列表
	$.ajax({
		'url': templateListApi,
		'type': 'get',
		'data': '',
		beforeSend: function () {
			swal({icon: 'success',className: 'alertloading',button:false,closeOnClickOutside: false});
		},
		success: function(data) {
			if(!statusCode(data.code)) return false;
			var list = '';
			for(var i=0; i<data.list.length; i++){
				list += '<li data-id="'+ data.list[i].id+'">';
				list += '<div class="editing"><span><i></i></span></div>';
				list += '<div class="template-thumbnail">';
				list += '<img src="'+data.list[i].thumbnail+'">';
				list += '</div>';
				list += '</li>';
			}
			$('#template ul').html(list);
			$('#template .keyword').val('');
			
			swal.close();
		},
		error: function(xhr, stat, err) {
			if(xhr.status != 404 && xhr.responseText) {
				loadSvgString(xhr.responseText);
			} else {
				swal('ERRO', uiStrings.notification.URLloadFail + ": \n"+err+'', 'error')
			}
		}
	});
	
	//点击获取更多模板
	var templateCategory = 'namecard',
		page = '1',
		pagelength = '10';
		
	$('#loadmore_template').click(function(){
		$.ajax({
			'url': templateListApi,
			'type': 'get',
			'data': '{"category":"'+templateCategory+'","page":"'+page+'","pagelength":"'+pagelength+'"}',
			beforeSend: function () {
				swal({icon: 'success',className: 'alertloading',button:false,closeOnClickOutside: false});
			},
			success: function(data) {
				if(!statusCode(data.code)) return false;
				var list = '';
				for(var i=0; i<data.list.length; i++){
					list += '<li data-id="'+ data.list[i].id+'">';
					list += '<div class="editing"><span><i></i></span></div>';
					list += '<div class="template-thumbnail">';
					list += '<img src="'+data.list[i].thumbnail+'">';
					list += '</div>';
					list += '</li>';
				}
				$('#template ul').append(list);
				$('#template .keyword').val('');
				
				swal.close();
			},
			error: function(xhr, stat, err) {
				if(xhr.status != 404 && xhr.responseText) {
					loadSvgString(xhr.responseText);
				} else {
					swal('ERRO', uiStrings.notification.URLloadFail + ": \n"+err+'', 'error')
				}
			}
		});
	})



});
	